package com.bawei.rk_01.fm

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Handler
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.utils.bean.Roll
import com.bawei.base.utils.mvvm.BaseFragment
import com.bawei.rk_01.Adapter.CouponsAdapter
import com.bawei.rk_01.Adapter.GoodsAdapter
import com.bawei.rk_01.Adapter.MenuAdapter
import com.bawei.rk_01.Adapter.MoneyAdapter
import com.bawei.rk_01.Adapter.NewAdapter
import com.bawei.rk_01.Home.HomeViewModel
import com.bawei.rk_01.R
import com.bawei.rk_01.Room.AppDBUtils
import com.bawei.rk_01.Room.LiveEntity
import com.bawei.rk_01.databinding.FragmentHomeBinding
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.loader.ImageLoader
import java.util.Timer
import java.util.TimerTask


class HomeFragment : BaseFragment<FragmentHomeBinding,HomeViewModel>() {

    //轮播图
    val list = ArrayList<String>()
    //适配器
    lateinit var menuAdapter: MenuAdapter
    lateinit var newAdapter: NewAdapter
    lateinit var moneyAdapter: MoneyAdapter
    //延时初始化 定时器
    lateinit var timer : Timer
    val handler = Handler()
    var index = 0 //新闻显示内容的下标

    //分页操作
    val limit = 5
    var page = 1
    var type = 4
    lateinit var goodsAdapter: GoodsAdapter

    //判断优惠卷是否领取
    var receive = 0

    //渲染礼物
    lateinit var couponsAdapter: CouponsAdapter

    override fun getViewModel(): Class<HomeViewModel> {
        return HomeViewModel::class.java
    }

    override fun getLayout(): Int {
        return R.layout.fragment_home
    }

    @SuppressLint("ResourceType")
    override fun initView() {

        //点击跳转
        binding.search.setOnClickListener {
            ARouter.getInstance().build("/app/SearchActivity").navigation()
        }

        viewModel.index()

        menuAdapter = MenuAdapter()
        binding.rv.layoutManager = GridLayoutManager(context,5)
        binding.rv.adapter = menuAdapter

        //点击跳转
        menuAdapter.setOnItemClickListener { adapter, view, position ->
            when(position){
                5->{
                    ARouter.getInstance().build("/app/CouponsActivity").navigation()
                }
                7->{
                    ARouter.getInstance().build("/app/AddressActivity").navigation()
                }
            }
        }

        newAdapter = NewAdapter()
        binding.rvNews.layoutManager = LinearLayoutManager(requireContext())
        binding.rvNews.adapter =newAdapter

        moneyAdapter = MoneyAdapter()
        binding.rvBargain.layoutManager = GridLayoutManager(requireContext(),4)
        binding.rvBargain.adapter = moneyAdapter

        //点击item ，下方商品数据发生变化
        moneyAdapter.setOnItemClickListener { adapter, view, position ->
            //点击是，type一定发生l变化
            type = moneyAdapter.data.get(position).type.toInt()
            //每次切换type，将page设为第一页
            page = 1
            viewModel.indexGoods(type, limit, page)
            //获取选择的下标
            moneyAdapter.setIndex(type)
        }

        //刷新
        binding.sm.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                viewModel.indexGoods(type, limit, page)
                binding.sm.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                viewModel.indexGoods(type, limit, page)
                binding.sm.finishLoadMore()
            }
        })

        //渲染列表
        goodsAdapter = GoodsAdapter()
        val gridl =  GridLayoutManager(requireContext(),2)
        binding.rvFenlei.layoutManager = gridl
        val ponition = gridl.findFirstVisibleItemPosition()
        binding.rvFenlei.adapter = goodsAdapter
        viewModel.indexGoods(type, limit, page)

        //点击跳转详情
        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/app/XqActivity").withInt("index",goodsAdapter.data.get(position).id).navigation()
        }

        //点击喜欢
        goodsAdapter.addChildClickViewIds(R.id.live)
        goodsAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.live->{
                    goodslive(position)
                }
            }
        }

        //渲染礼物
        viewModel.getcoupons(3,1,1)
        couponsAdapter = CouponsAdapter()
        binding.rvCoupons.adapter = couponsAdapter
        //点击优惠卷，领取
        couponsAdapter.setOnItemClickListener { adapter, view, position ->
            receive = position
            viewModel.receive(couponsAdapter.data.get(position).id)
        }

    }

    //点击喜欢,再次点击取消喜欢
    fun goodslive(position:Int){
        val query = AppDBUtils.getDB().liveDao().query(goodsAdapter.data.get(position).storeName)
        if (query == null){
            AppDBUtils.getDB().liveDao().insert(LiveEntity(goodsAdapter.data.get(position).id,goodsAdapter.data.get(position).storeName,goodsAdapter.data.get(position).image))
            ToastUtils.showLong("点赞")
            val imageView = goodsAdapter.getViewByPosition(position, R.id.live) as ImageView
            imageView.setImageResource(R.drawable.baseline_favorite_24)
        }else{
            AppDBUtils.getDB().liveDao().delete(query)
            ToastUtils.showLong("取消点赞")
            val imageView = goodsAdapter.getViewByPosition(position, R.id.live) as ImageView
            imageView.setImageResource(R.drawable.baseline_favorite_border_24)
        }
    }

    override fun initData() {

        viewModel.indexsuccess.observe(this){
            ToastUtils.showLong("1234555")
            if (it.code == 200){
                ToastUtils.showLong("你好")

                //轮播图
                it.data.banner.forEach {
                    list.add(it.pic)
                }
                binding.banner.setImages(list)
                binding.banner.setImageLoader(object : ImageLoader() {
                    override fun displayImage(
                        context: Context?,
                        path: Any?,
                        imageView: ImageView?
                    ) {
                        if (context!=null && imageView!=null){
                            ToastUtils.showLong("你好")
                            Glide.with(context).load(path).into(imageView)
                        }
                    }
                }).start()

                //菜单
                menuAdapter.data.clear()
                menuAdapter.data.addAll(it.data.menus)
                menuAdapter.notifyDataSetChanged()

                //新闻
                newAdapter.data.clear()
                newAdapter.data.addAll(it.data.roll)
                newAdapter.data.add(Roll(2,"你好你好","",""))
                menuAdapter.data.forEachIndexed { index, menu ->
                    newAdapter.data.add(Roll(1,menu.name,"",""))
                }
                newAdapter.notifyDataSetChanged()

                //新闻内容没两秒显示下一条新闻内容
                timer = Timer()
                timer.schedule(object : TimerTask() {
                    override fun run() {
                        handler.post {
                            binding.rvNews.scrollToPosition(index)
                            index++
                            if (index == newAdapter.data.size){
                                index = 0
                            }
                        }
                    }
                },0,2000)

                //优惠
                moneyAdapter.data.clear()
                moneyAdapter.data.addAll(it.data.explosiveMoney)
                moneyAdapter.notifyDataSetChanged()

            }else{
                ToastUtils.showLong(it.message)
            }
        }

        //渲染首页商品
        viewModel.goodssuccess.observe(this){
            if (it.code == 200){
                if (page == 1){
                    goodsAdapter.data.clear()
                }
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
                if (it.data.list.size  == 0){
                    ToastUtils.showLong("没有更多商品了，请切换种类")
                }
            }else{
                ToastUtils.showLong(it.message)
            }
        }

        //渲染优惠卷
        viewModel.couponssuccess.observe(this){
            if (it.code == 200){
                couponsAdapter.data.clear()
                couponsAdapter.data.addAll(it.data)
                couponsAdapter.notifyDataSetChanged()
            }
        }

        //领取优惠卷
        viewModel.receivesuccess.observe(this){
            if (it.code == 200){
                val textView = couponsAdapter.getViewByPosition(receive, R.id.lq) as TextView
                textView.text = "已\n领\n取"
                ToastUtils.showLong("领取成功")
            }
        }


    }

}